package crawler;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import log.Log;
import log.Log.priority;

import shared.Convert;
import shared.Friend;

import database.FromFileToDatabase;
import form.ProgressBar;


public class PageAnalyzer 
{
	
    String pageSource;
    
    PageAnalyzer()
    { }
    
	public void loadPageSource(HttpURLConnection connection)
	{
		try
		{
			InputStream stream = connection.getInputStream();
			pageSource = Convert.StreamToString(stream);
		}
		catch(IOException io)
		{
			io.printStackTrace();
		}		
	}
	
	private String readName(String string)
	{
		return string.substring(0, string.lastIndexOf(" "));
	}
	private String readSurname(String string)
	{
		return string.substring(string.lastIndexOf(" ") + 1);
	}
	
	private Friend readFriend(String string)
	{
		String name, surname, id, gender = null, age = null, birthplace = null, currentplace = null;
		String[] lines = string.split("\n");
		name = readName(lines[1]);
		surname = readSurname(lines[1]);
		id = lines[0];
		if(lines.length >= 3)
			gender = lines[2];
		if(lines.length >= 5)
		{
			if((lines[4] != null) && (lines[4] != null))
				birthplace = lines[4].split(",")[0];
			if((lines.length > 5) && (lines[4] != null) && (lines[4] != null))
				currentplace = lines[5].split(",")[0];
		}
		if((lines.length > 3) && (!lines[3].isEmpty()))
		{
			Pattern pattern = Pattern.compile("\\d\\d\\/\\d\\d\\/\\d\\d\\d\\d");
			Matcher matcher = pattern.matcher(lines[3]);
			if(matcher.matches())
				age = Integer.toString(Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(lines[3].substring(lines[3].length()-4)));
		}
		return new Friend(name, surname, id, gender, birthplace, currentplace, age);
	}
	
	private Friend readMutualFriend(String firstline, String id)
	{
		String name, surname;
		name = readName(firstline);
		surname = readSurname(firstline);
		return new Friend(name,surname,id);
	}
	
	private Friend readFamilyMember(String[] string)
	{
		String name, surname, id;
		name = readName(string[0]);
		surname = readSurname(string[0]);
		id = string[1];
		return new Friend(name,surname,id);
	}
	
	private String[] splitFriends()
	{
		String string = pageSource.substring(pageSource.indexOf("\n")+1);
		String[] array =  string.split("\\d\\.");
		return Arrays.copyOfRange(array, 1, array.length);
	}
	
	public void saveAllFromFile()
	{
		if(!pageSource.isEmpty())
		{
			String profileid = getProfileId();
			ProgressBar.get().setValueDynamic(10);
			saveSource();
			ProgressBar.get().setValueDynamic(15);
			String[] strings = splitFriends();
			for(String i : strings)
			{
				saveFriend(i, profileid);
				if(ProgressBar.get().getValue() < 95)
					ProgressBar.get().setValueDynamic(ProgressBar.get().getValue()+1);
			}
			ProgressBar.get().setValueDynamic(100);
			Log.console("Pobieranie danych z pliku zako�czone pomy�lnie", priority.Message);
		}
		else
			Log.console("Plik niedost�pny lub b��d po��czenia z internetem", priority.Error);
	}
	
	private void saveSource()
	{
		String source, name, surname;
		source = pageSource.substring(pageSource.indexOf("\n") + 1,pageSource.indexOf("\n1.\n"));
		name = readName(source);
		surname = readSurname(source);
		FromFileToDatabase.insertSource(getProfileId(), name, surname);
		/*
		Friend friend = new Friend(getProfileId(), null, null);
		FromFileToDatabase.insertFriend(friend);*/
	}
	
	private void saveProfileInfo(String profileid)
	{
		Friend friend = new Friend(profileid, null, null);
		FromFileToDatabase.insertFriend(friend);
		//TODO Do zaktualizowania, je�eli b�dziemy mie� wi�cej informacji.
	}
	
	private void saveFriend(String string, String profileid)
	{
		string = string.substring(1);
		String friendid = getFriendId(string);
		saveInfo(string, profileid);
		saveFamily(string, friendid);
		saveMutualFriends(string, friendid, profileid);
		saveEducation(string, friendid);
		saveWork(string, friendid);
	}
	
	private String getProfileId()
	{
		return pageSource.substring(0, pageSource.indexOf("\n"));	
	}

	private String getFriendId(String string)
	{
		return string.substring(0, string.indexOf("\n"));
	}

	private void saveInfo(String string, String profileid)
	{
		String friendInfo = string.substring(0, string.indexOf("\nRodzina:"));
		Friend friend = readFriend(friendInfo);
		FromFileToDatabase.insertFriend(friend);
		//FromFileToDatabase.insertFriendship(profileid, friend.getId());
	}
	
	private void saveFamily(String string, String friendId)
	{
		String friendfamily = getStringSection(string, "Rodzina:\n", "\nWspolni znajomi");
		if(!friendfamily.isEmpty())
		{
			String[] familymembers =  friendfamily.split("\n");
			for(int i = 0; i < familymembers.length; i = i + 3)
			{
				String[] memberstring = {familymembers[i],familymembers[i+2]};
				Friend member = readFamilyMember(memberstring);
				saveFamilyMember(member, friendId, familymembers[i+1]);	
			}
		}
	}
	
	private void saveFamilyMember(Friend member, String friendid, String relation)
	{
		FromFileToDatabase.insertFriend(member);
		FromFileToDatabase.insertFamily(friendid, member.getId(), relation);
	}
	
	private void saveMutualFriends(String string,String friendid, String profileid)
	{
		String mutualfriends = getStringSection(string, "Wspolni znajomi:\n", "\nEdukacja");
		if(!mutualfriends.isEmpty())
		{
			String[] mutuals =  mutualfriends.split("\n");
			for(int i = 0; i < mutuals.length; i = i + 2)
			{
				Friend friend = readMutualFriend(mutuals[i], mutuals[i+1]);
				FromFileToDatabase.insertFriend(friend);
				FromFileToDatabase.insertFriendship(friend.getId(), friendid);
			}
		}
	}
	
	private void saveEducation(String string, String friendid)
	{
		String educationstring = getStringSection(string, "Edukacja:\n", "\nPraca");
		if((!educationstring.isEmpty()) && (educationstring != "\n\n"))
		{
			String schools[] = educationstring.split("\n\n\n\n");
			for(String s : schools)
			{
				if((!s.isEmpty()) && (s != "\n"))
				{
					String lines[] = s.split("\n");
					if(lines.length >= 4)
					{
						FromFileToDatabase.insertEducation(friendid, lines[1], lines[0], lines[3], lines[2]);
						if(lines.length >= 6)
						{
							Friend schoolfriend;
							for(int i = 4; i < lines.length; i = i + 2)
							{
								schoolfriend = new Friend(lines[i].substring(0, lines[i].lastIndexOf(" ")), lines[i].substring(lines[i].lastIndexOf(" ") + 1), lines[i+1]);
								FromFileToDatabase.insertFriend(schoolfriend);
								FromFileToDatabase.insertFriendship(friendid, schoolfriend.getId());
								FromFileToDatabase.insertEducation(schoolfriend.getId(), lines[1], lines[0], lines[3], lines[2]);
							}							
						}
					}
				}
			}
		}		
	}
	
	private void saveWork(String string, String friendid)
	{
		if(!string.isEmpty())
		{
			String workstring;
			workstring = getStringSection(string, "Praca:\n", "\n\n\n\n");
			if(!workstring.isEmpty())
			{				
				String[] lines = workstring.split("\n");
				for(int i = 0; i < lines.length - 1; i = i + 2)
				{
					FromFileToDatabase.insertWork(lines[i], lines[i+1],friendid);
				}
			}
		}		
	}
	
	private String getStringSection(String string, String start, String end)
	{
		if(end == null)
			return string.substring(string.indexOf(start)+start.length());
		else
			return string.substring(string.indexOf(start)+start.length(), string.lastIndexOf(end));
	}
}
